<?php
include '../includes/cPlayer.php';
include '../includes/cDatabase.php';
include '../includes/cPage.php';
include '../includes/cDates.php';

$cPage = new page("Create XML");
echo $cPage->getTitle();
echo $cPage->pageStringStart();
echo $cPage->contentStringStart();

if (@$_GET['form'] == "yes")
{
	// Check user and password
	if ($_POST['fileName'])
	{
		searchFileForString($_POST['fileName']);
	}
	else
	{
		echo "ERROR: No Filename.";
	}
	?>
	<div align="center">
	<form action="<?php echo $_SERVER['PHP_SELF'] ?>?form=yes" method="POST">
	  <table width='400' border='0'>
		<tr>
		  <td colspan="2" align="center">
			  <INPUT TYPE="BUTTON" VALUE="Main Menu" ONCLICK="window.location.href='http://localhost'"></td>
	 	</tr>
	  </table>
	</form>
	</div>
	
	<?php
}
else
{
?>
<div align="center">
<form action="<?php echo $_SERVER['PHP_SELF'] ?>?form=yes" method="POST">
  <table width='400' border='0'>
    <tr>
      <td><div align="center">Filename</div></td>
    </tr>
    <tr>
      <td><div align="center">
        <input type='text' name='fileName' size='20' maxlength='30' value=<?php echo @$_POST['fileName'] ?>>
      </div></td>
    </tr>
	<tr>
	  <td colspan="2" align="center">
	    <p>&nbsp;</p>
	    <p><input name="loginButton" type="submit" id="login" value="CREATE">
	       <INPUT TYPE="BUTTON" VALUE="Main Menu" ONCLICK="window.location.href='http://ttvuk03703'">
        </p></td>
 	</tr>
  </table>
</form>
</div>

<?php
}
function AddPlayerToDB($cPlayer)
{
	$error = 0;
	
	if (!$error)
	{
		$cDatabase = new database();

		$connect = $cDatabase->connectToDatabase();
		$activeDatabase = $cDatabase->getActiveDatabase($connect);
	
		$db = $cDatabase->selectDatabase($connect, $activeDatabase);
		
		// Check code does not already exist in DB
		$selectArray[0] = '*';
		$result = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, "playerCode", $cPlayer->getPlayerCode(), NULL, NULL);
		if ($result)
		{
			$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
			if ($cPlayer->getPlayerCode() == $row['playerCode'])
			{
				// We already found the player in the database.
				echo "<BR>ERROR: Code ".$cPlayer->getPlayerCode()." already exists: ";
				echo $row['playerCode']." ".$row['playerName']." ".$row['playerTeam']." £".$row['playerValue']."m ".$row['playerPosition'];
				
				// Check to see if this player has changed teams.
				if ($row['playerTeam'] != $cPlayer->getPlayerTeam())
				{
					echo "<BR>ERROR: Code ".$cPlayer->getPlayerCode()." has changed teams from ".$row['playerTeam']." to ".$cPlayer->getPlayerTeam();
					$cDatabase->updatePlayer ($connect, 'playerTeam', $cPlayer->getPlayerTeam(), $cPlayer->getPlayerCode());
				}
			}
			else
			{
				// Add a row to the table
				$cDatabase->insertPlayer($connect, $cPlayer->getPlayerCode(), $cPlayer->getPlayerName(),
					$cPlayer->getPlayerTeam(), $cPlayer->getPlayerValue(), $cPlayer->getPlayerPosition(), $cPlayer->getPlayerLastYearScore() );
			}
		}
		else
		{
			echo "<BR>ERROR:DB Error";
		}
	}
	else
	{
		echo "<BR>ERROR: Player has not been added";
	}
}

function searchFileForString($file) 
{
	$PlayerCount = 0;
	$tempPlayerCode = array();
	
	$section = file_get_contents($file, true);
	if ($section != FALSE)
	{	
		// e,g, 2009
		// <tr class='' id='plaid-2002-DEF'><td class='info-icon'></td><td class='name'>Terry, J</td><td class='team'>CHE</td><td class='last_pts'>122</td><td class
		
		// e.g. 2010 attempt2
		// <tr id='p1001'><td>van der Sar, E</td><td>MUN</td><td>3.9</td><td>10.2%</td><td>77</td><td>0</td></tr>
		
		// e.g. 2010
		// <tr class=' ro' id='plaid-1003-GK'>
		//<td class='name'>Reina, J</td>
		//<td class='team'>LIV</td>
		//<td class='team_name'>Liverpool</td>
		//<td class='value'>&pound;3.8m</td>
		//<td class='pcsel'>14.2%</td>
		//<td class='last_pts'>117</td>
		//<td class='last_runs'>-</td>
		//</tr>
		
		//<div id='player-selection'><ul id='group-menu'><li id='menu-GK-1' dir='DESC'><span>GoalKeeper</span></li><li id='menu-DEF-2' dir='DESC'><span>Defender</span></li><li id='menu-MID-3' dir='DESC'><span>Midfielder</span></li><li id='menu-STR-4' dir='DESC'><span>Striker</span></li></ul><div id='player-head'><table><tr><th class='name'>Name</th><th class='team_name'>Team</th><th class='value'>Value</th>    <th class='pcsel'>% Selected</th><th class='last_pts'>10/11 Points</th><th id='goals-sheets' class='last_runs'>10/11 Goals</th><th class='compare'>Compare</th></tr></table></div> <!-- #player-head --><p id='list-loading'>loading player list...</p><div id='player-lists'><div class='pla-list' id='list-GK'><table>
		//<tr id='p1001'><td>Hart, J</td><td>MCY</td><td>4.0</td><td>24.4%</td><td>173</td><td>23</td> <td class='compare'><input type='checkbox' value='y' id='compare_1001' name='compare_1001' class='compare-box'></td><td class='hiddencol' id='comparison_1001'>173|46/0|1|1/0|23/0|&pound;4.0m</td></tr>
		
		$PlayerIdPattern = "/<tr id='p/";
		$PlayerNameStartPattern = "/<td>/";
		$PlayerNameEndPattern2009 = "/<\/td><td class='team'/";
		$PlayerNameEndPattern = "/<\/td>/";
		$PlayerTeamPattern = "/<\/td><td>/";
		$PlayerLastPointsStartPattern = "/<\/td><td>/";
		$PlayerLastPointsEndPattern2009 = "/<\/td><td class='value'/";
		$PlayerLastPointsEndPattern = "/<\/td>/";
		$PlayerValueStartPattern2009 = "/'value'/";
		$PlayerValueStartPattern = "/<\/td><td>/";
		$PlayerValueEndPattern = "/<\/td>/";
		
		//$PlayerIdPattern = "/plaid-/";
		//$PlayerNameStartPattern = "/'name'/";
		//$PlayerNameEndPattern2009 = "/<\/td><td class='team'/";
		//$PlayerNameEndPattern = "/<\/td>/";
		//$PlayerTeamPattern = "/'team'/";
		//$PlayerLastPointsStartPattern = "/'last_pts'/";
		//$PlayerLastPointsEndPattern2009 = "/<\/td><td class='value'/";
		//$PlayerLastPointsEndPattern = "/<td class='last_runs'/";
		//$PlayerValueStartPattern2009 = "/'value'/";
		//$PlayerValueStartPattern = "/'value'>&pound/";
		//$PlayerValueEndPattern = "/m<\/td>/";
		
		
		$PlayerIdFixedOffset = strlen($PlayerIdPattern) - 2;	// Length minus the 2 slashes
		//$PlayerPosnFixedOffset = strlen($PlayerIdPattern) + 3;
		$PlayerNameStartFixedOffset = strlen($PlayerNameStartPattern) - 2;	// Length minus the 2 slashes
		$PlayerTeamFixedOffset = strlen($PlayerTeamPattern) - 3;
		$PlayerLastPointsStartFixedOffset = strlen($PlayerLastPointsStartPattern) - 3;
		$PlayerValueStartFixedOffset = strlen($PlayerValueStartPattern) - 3;
		
		$offset = 0;
		
		while(preg_match($PlayerIdPattern, $section, $matches, PREG_OFFSET_CAPTURE, $offset))
		{
			$PlayerCount++;
    
			$PlayerIdOffset = $matches[0][1] + $PlayerIdFixedOffset;		// Index into $section string to where the player code ID starts
			$PlayerPosnOffset = $matches[0][1] + $PlayerPosnFixedOffset;	// Index into $section string to where the player position starts e.g. GK, DEF, MID, STR
			
			$PlayerCodeArray = array($section[$PlayerIdOffset],$section[$PlayerIdOffset+1],$section[$PlayerIdOffset+2],$section[$PlayerIdOffset+3]);
			
			//if ($section[$PlayerPosnOffset]=="G")
			//{
				// GK is only 2 characters
			//	$PlayerPosnArray = array($section[$PlayerPosnOffset],$section[$PlayerPosnOffset+1]);
			//}
			//else
			//{
				// DEF, MID, STR is 3 characters
			//	$PlayerPosnArray = array($section[$PlayerPosnOffset],$section[$PlayerPosnOffset+1],$section[$PlayerPosnOffset+2]);
			//}
			
			$PlayerCode = implode($PlayerCodeArray);
			//$PlayerPosn = implode($PlayerPosnArray);
			if ($PlayerCode < 2000) $PlayerPosn = 'GK';
			else if ($PlayerCode < 3000) $PlayerPosn = 'DEF';
			else if ($PlayerCode < 4000) $PlayerPosn = 'MID';
			else $PlayerPosn = 'ATT';
			
			if ($PlayerPosn == 'STR')
			{
				$PlayerPosn = 'ATT';
			}
			
			echo"<BR><BR>Code:$PlayerCode Posn:$PlayerPosn";
			
			$offset = $PlayerIdOffset;
			
			// Find start of Player Name
			if (preg_match($PlayerNameStartPattern, $section, $matches, PREG_OFFSET_CAPTURE, $offset))
			{
				$PlayerNameStartOffset = $matches[0][1] + $PlayerNameStartFixedOffset;

				// Find end of player name (Name can be of variable length
				if (preg_match($PlayerNameEndPattern, $section, $matches, PREG_OFFSET_CAPTURE, $offset)) 
				{
					$PlayerNameEndOffset = $matches[0][1];
					$PlayerNameArray = array();
					
					//echo "<BR>End $PlayerNameEndOffset Start $PlayerNameStartOffset";
					for ($count = 0; $count < ($PlayerNameEndOffset-$PlayerNameStartOffset); $count++)
					{
						$PlayerNameArray[$count] = $section[$PlayerNameStartOffset+$count];
					}
					$PlayerName = implode($PlayerNameArray);
					
					$PlayerName = str_replace("'", "\'", $PlayerName);
					
					echo " Name: $PlayerName";
				}
			}

			// Find Player team
			if (preg_match($PlayerTeamPattern, $section, $matches, PREG_OFFSET_CAPTURE, $offset))
			{
				$PlayerTeamOffset = $matches[0][1] + $PlayerTeamFixedOffset;
				$PlayerTeamArray = array($section[$PlayerTeamOffset],$section[$PlayerTeamOffset+1],$section[$PlayerTeamOffset+2]);
					
				$PlayerTeam = implode($PlayerTeamArray);
				echo " Team: $PlayerTeam";
			}
	
			$offset = $PlayerTeamOffset;
			
			// Find value
			if (preg_match($PlayerValueStartPattern, $section, $matches, PREG_OFFSET_CAPTURE, $offset))
			{
				$PlayerValueStartOffset = $matches[0][1] + $PlayerValueStartFixedOffset;

				// Find end of player name (Name can be of variable length
				if (preg_match($PlayerValueEndPattern, $section, $matches, PREG_OFFSET_CAPTURE, $PlayerValueStartOffset)) 
				{
					$PlayerValueEndOffset = $matches[0][1];
					$PlayerValueArray = array();
					
					for ($count = 0; $count < ($PlayerValueEndOffset-$PlayerValueStartOffset); $count++)
					{
						$PlayerValueArray[$count] = $section[$PlayerValueStartOffset+$count];
					}
					$PlayerValue = implode($PlayerValueArray);
					echo " Value: $PlayerValue";
				}
			}
			
			$offset = $PlayerValueEndOffset+10; // Jump over %

			// Find Last points
			if (preg_match($PlayerLastPointsStartPattern, $section, $matches, PREG_OFFSET_CAPTURE, $offset))
			{
				$PlayerLastPointsStartOffset = $matches[0][1] + $PlayerLastPointsStartFixedOffset;
				
				// Find end of last points(Name can be of variable length
				
				$offset = $PlayerLastPointsStartOffset;
				if (preg_match($PlayerLastPointsEndPattern, $section, $matches, PREG_OFFSET_CAPTURE, $offset)) 
				{
					$PlayerLastPointsEndOffset = $matches[0][1];
					$PlayerLastPointsArray = array();
					
					for ($count = 0; $count < ($PlayerLastPointsEndOffset-$PlayerLastPointsStartOffset); $count++)
					{
						$PlayerLastPointsArray[$count] = $section[$PlayerLastPointsStartOffset+$count];
					}
					$PlayerLastPoints = implode($PlayerLastPointsArray);
					// If this is a '-', change the value to a zero
					if /*($PlayerLastPoints == "-")*/($PlayerLastPointsEndOffset==$PlayerLastPointsStartOffset)
					{
						$PlayerLastPoints = 0;
					}
					echo " LastPTS: $PlayerLastPoints";
				}
			}
			
			$tempPlayerCode[$PlayerCount] = $PlayerCode;	
			
			$cPlayer[$PlayerCount] = new player($PlayerCode);
	
			$error |= $cPlayer[$PlayerCount]->addPlayerName($PlayerName);
			$error |= $cPlayer[$PlayerCount]->addPlayerTeam($PlayerTeam);
			$error |= $cPlayer[$PlayerCount]->addPlayerValue($PlayerValue);
			$error |= $cPlayer[$PlayerCount]->addPlayerPosition($PlayerPosn);
			$error |= $cPlayer[$PlayerCount]->addPlayerLastYearScore($PlayerLastPoints);
			
			AddPlayerToDB($cPlayer[$PlayerCount]);
		}
		// All players are stored in $cPlayer[$PlayerCount]
		// go through player list and see if there are any players that have been removed.
		$cDatabase = new database();

		$connect = $cDatabase->connectToDatabase();
		$activeDatabase = $cDatabase->getActiveDatabase($connect);
	
		$db = $cDatabase->selectDatabase($connect, $activeDatabase);
		
		$selectArray[0] = '*';
		
		$result = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, "playerCode", $playerCode, NULL, NULL);
		
		for ($i = 0; $i < mysqli_num_rows($result); $i++)
		{
			//echo"<BR>db code ".$row['playerCode'];
			$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
			$found = 0;
			
			for ($count = 0; $count < $PlayerCount; $count++)
			{
				//echo"<BR>db".$row['playerCode']." tele ".$tempPlayerCode[$count];
				if ($tempPlayerCode[$count] == $row['playerCode'])
				{
					// The player from the website is in the database so break out
					$found = 1;
					break;
				}
			}
			if ($found == 0)
			{
				// This player has been removed from the Telegraph website but it's in our database so set it to inactive.
				echo"<BR>Player need to go:".$row['playerCode'];
			}
		}
	}
	else
	{
		echo "<BR>ERROR: opening file ".$file;
	}	
}
echo $cPage->getContentStringEnd();
echo $cPage->getMenu();
echo $cPage->getClear();
echo $cPage->pageStringEnd();
echo $cPage->getFooter();
?>